package com.smarthospital.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.AddSmsSignRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.smarthospital.common.Result.CodeMsg;
import com.smarthospital.common.Result.CommonException;
import com.smarthospital.contants.SHConst;
import com.smarthospital.service.OptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * create by sym  2021/5/4 15:31.
 */
@Service
@Slf4j
public class OptServiceImpl implements OptService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private Client client;
    @Value("${aliyun.sms.one.signName}")
    private String signName;
    @Value("${aliyun.sms.one.templateCode}")
    private String templateCode;

    /**
     * @param code
     * @param phone
     */
    @Override
    public void send(int code, String phone) throws Exception {
        // 1.发送短信
        SendSmsRequest sendReq = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName(signName)
                .setTemplateCode(templateCode)
                //短信模板变量对应的实际值，JSON格式  {"code":"1111"}
                .setTemplateParam("{\"code\":\""+code+"\"}");
        SendSmsResponse sendResp = client.sendSms(sendReq);
        SendSmsResponseBody body = sendResp.body;
        log.info("【发送短信】 out {}", JSON.toJSONString(body));
        if (!"ok".equalsIgnoreCase(body.code)) {
            throw new CommonException(CodeMsg.ERROR_OPT_SEND);
        }
    }

    @Override
    public void checkCode(Long userId, String checkPhone, Integer type,String checkCode) {
        String key = String.format(SHConst.redis_key.bus_optSend,userId,type,checkPhone);
        String code = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(code)) {
            throw new CommonException(CodeMsg.ERROR_OPT_MISS,"验证码过期");
        }
        if (!code.equals(checkCode)) {
            throw new CommonException(CodeMsg.ERROR_OPT_MISS,"验证码不正确");
        }
    }
}
